/*
 * @# UserController.java 2011-12-15 上午09:49:40
 * 
 * Copyright (C) 2010 - 2011 广州羿安信息科技有限公司
 * Guangzhou ianswer information technology co. ltd.
 * 
 * All rights reserved!
 */
package com.ianswer.px.user.action;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ianswer.common.security.crypto.CryptoUtils;
import com.ianswer.common.util.time.SecondsUtils;
import com.ianswer.common.util.web.ServletUtils;
import com.ianswer.px.common.SessionContextHolder;
import com.ianswer.px.user.entity.User;
import com.ianswer.px.user.entity.UserSession;
import com.ianswer.px.user.redis.UserRedis;
import com.ianswer.px.user.service.UserService;
import com.ianswer.px.utils.AppPropReader;
import com.ianswer.px.utils.SendEmailUtils;

/**
 * @author lunx
 */
@Controller
public class HomeController {

	private static final String DESKEY = "YIANKEJI_PINGXIUWANG";

	/**
	 * 激活分隔符
	 */
	private static final String SEPA = "#";

	private static final Logger log = Logger.getLogger(HomeController.class);

	@Resource(name = "userService")
	private UserService userService;

	/**
	 * 跳转到注册
	 * @return
	 */
	@RequestMapping(value = "/register", method = RequestMethod.GET)
	public String register() {
		return "user/register";
	}

	/**
	 * 注册
	 * @param user
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/register", method = RequestMethod.POST)
	public String register(User user, Model model, HttpServletRequest request) {
		if (StringUtils.isBlank(user.getEmail()) || StringUtils.isBlank(user.getPassword())) {
			model.addAttribute("msg", "注册失败，请填写完整的注册信息！");
			return "user/register";
		}
		if (!user.getPassword().equals(user.getConfirmPwd())) {
			model.addAttribute("msg", "注册失败，两次密码不一致！");
			return "user/register";
		}
		user.unactivate();
		user.setRegDate(SecondsUtils.seconds());
		user.setRegIp(ServletUtils.getIpAddrLong(request));
		try {
			User oldUser = userService.getUserByCode(user.getEmail());
			if (oldUser != null) {
				model.addAttribute("msg", "注册失败，该用户已存在！");
				return "user/register";
			}
			userService.insertUser(user);
			try {
				sendEmail(user.getEmail(), user.getEmail(), genUrl(user.getId(), user.getEmail()));
				model.addAttribute("msg", "注册成功，请前往邮箱激活！");
			} catch (Exception e) {
				model.addAttribute("msg", "注册成功，激活邮件发送失败，请稍后登录激活！");
				log.error(e.getMessage(), e);
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			model.addAttribute("msg", "注册失败！");
		}
		return "user/register";
	}

	/**
	 * 激活
	 * @param verify
	 * @param check
	 * @return
	 */
	@RequestMapping(value = "/activate", method = RequestMethod.GET)
	public @ResponseBody
	String activate(@RequestParam("verify") String verify, @RequestParam("check") String check) {
		if (StringUtils.isBlank(verify) || StringUtils.isBlank(check)) {
			return "激活失败！";
		}
		try {
			String params = CryptoUtils.desedeDecryptFromBase64(verify, Base64.encodeBase64(DESKEY.getBytes()));
			String checkValue = StringUtils.substring(params, 0, StringUtils.lastIndexOf(params, SEPA));
			String checkMd5 = DigestUtils.md5Hex(checkValue.getBytes());
			if (!check.equals(checkMd5)) {
				return "激活失败！";
			}
			String userCode = StringUtils.substring(checkValue, StringUtils.lastIndexOf(checkValue, SEPA) + 1);
			userService.updateUserState(userCode);
			//加入session
			User user = userService.getUserByCode(userCode);
			setUserSession(user);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return "激活失败！";
		}
		return "<a href=" + AppPropReader.getProperties("login.url") + ">激活成功，请登录！</a>";
	}

	/**
	 * 跳转到登录
	 * @return
	 */
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login() {
		return "user/login";
	}

	/**
	 * 登录
	 * @param userCode
	 * @param userPwd
	 * @param session
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String login(@RequestParam("userCode") String userCode, @RequestParam("userPwd") String userPwd, Model model) {
		if (StringUtils.isBlank(userCode) || StringUtils.isBlank(userPwd)) {
			model.addAttribute("msg", "登录信息不能为空！");
			return "user/login";
		}
		User user = userService.checkUser(userCode, userPwd);
		if (user == null) {
			model.addAttribute("msg", "登录失败，密码错误或用户不存在！");
			return "user/login";
		}
		if (user.isForbidden()) {
			model.addAttribute("msg", "登录失败，该帐号已禁用！");
			return "user/login";
		}
		if (user.isActivate()) {
			model.addAttribute("msg", "该帐号未激活，请前往邮箱激活后再登录！");
			try {
				sendEmail(user.getEmail(), user.getEmail(), genUrl(user.getId(), user.getEmail()));
			} catch (Exception e) {
				log.error(e.getMessage(), e);
			}
			return "user/login";
		}
		setUserSession(user);
		return "redirect:/home";
	}

	/**
	 * 设置登录用户信息在session中存储
	 * @param user
	 * @param session
	 */
	private void setUserSession(User user) {
		UserSession userSession = new UserSession();
		userSession.setUserId(user.getId());
		userSession.setUserType(user.getUserType());
		userSession.setEmail(user.getEmail());
		userSession.setAvatar(user.getAvatar());
		
		if (null == UserRedis.get(user.getId())) {
			UserRedis.init(user);
		}
		SessionContextHolder.currentUser(userSession);
	}

	/**
	 * 登出
	 */
	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public String logout(HttpSession session) {
		session.invalidate();
		return "redirect:/login";
	}

	/**
	 * 检查用户是否存在
	 * @param userCode
	 * @return
	 */
	@RequestMapping(value = "/checkUserCode", method = RequestMethod.GET)
	public @ResponseBody
	boolean checkUserCode(@RequestParam("email") String email) {
		User user = userService.getUserByCode(email);
		if (user == null) {
			return true;
		}
		return false;
	}

	/**
	 * 生成激活URL
	 * @param id
	 * @param userCode
	 * @return
	 */
	private static String genUrl(Long id, String userCode) {
		String baseUrl = AppPropReader.getProperties("register.activate.url");
		String verify = id + "#" + userCode;
		baseUrl += "?check=" + DigestUtils.md5Hex(verify);
		verify += "#" + RandomUtils.nextInt();
		baseUrl += "&verify="
				+ CryptoUtils.desedeEncryptToBase64URLSafe(verify, Base64.encodeBase64(DESKEY.getBytes()));
		return baseUrl;
	}

	/**
	 * 激活Email发送
	 * @param userCode
	 * @param nickName
	 * @param url
	 */
	private static void sendEmail(String userCode, String nickName, String url) {
		SendEmailUtils.sendHtml(userCode, "品秀网注册帐号激活", "亲爱的" + nickName
				+ "：<br/>欢迎加入品秀网！<br/>请点击下面链接完成注册：<br/><a href='" + url + "'>" + url + "</a>"
				+ "<br/>如果以上链接无法点击，请将上面地址复制到你的浏览器的地址栏进入品秀网。<br/>--品秀网（这是一封自动产生的emial，请勿回复。）");
	}
}
